const service = require('../../utils/service.js');
const api = require('../../utils/util.js');

// pages/cart/cart.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isWrite: false, //--删除与结算
    allCheck: false, //--全选
    totalMoney: '0.00', //--总的金钱
    is_goodsNumber: true, //--数量改变是否完成
    cartList: [], //--商品总共数
    allGoodsNumber: 0, //--商品选择数量
    checkGoodsNumber: 0, //--商品选择数量
    checkGoodsChange: 0, //--改变商品数量
    goodsChange: false
  },
  //--数据加载
  init: function(callback) {
    let self = this;
    api.ajax(service.url('getCartList'), {}, function(res) {
      //console.log(JSON.stringify(res));
      if (res.code == 0) {
        let data = res.data,
          _number = 0,
          diableNumber = 0;
        if (Array.isArray(data) && data.length > 0) {
          for (let i = 0; i < data.length; i++) {
            data[i].check = false;
            for (let j = 0; j < data[i].cart.length; j++) {
              data[i].cart[j].check = false;
              _number++;
              if (data[i].cart[j].show_str == 1) {
                diableNumber++;
              }
            }
          }
          self.setData({
            cartList: data,
            allGoodsNumber: _number,
            checkGoodsChange: diableNumber
          });
          console.log(self.data.cartList);
        } else {
          self.setData({
            cartList: []
          });
          api.toast("购物车没有任何数据！");
        }
      } else {
        api.toast("数据出现错误！");
      }
      typeof callback == 'function' ? callback() : false;
    });
  },
  //--设置商品选择属性（true/false）  
  goodsCheckAllSet: function(checkBol, index) {
    let bol = checkBol == true ? true : false,
      shop = index && typeof(index) == 'number' ? index : false;
    if (shop) {
      for (let j = 0; j < this.data.cartList[shop].cart.length; j++) {
        if (this.data.cartList[shop].cart[j].show_str != 1 || this.data.goodsChange) {
          this.setData({
            [`cartList[${shop}].cart[${j}].check`]: bol
          });
        }
      }
    } else {
      for (let i = 0; i < this.data.cartList.length; i++) {
        this.setData({
          [`cartList[${i}].check`]: bol
        });
        for (let j = 0; j < this.data.cartList[i].cart.length; j++) {
          if (this.data.cartList[i].cart[j].show_str != 1 || this.data.goodsChange) {
            this.setData({
              [`cartList[${i}].cart[${j}].check`]: bol
            });
          }
        }
      }
    }
  },
  //--上选择数量
  goodsCheckNumber: function() {
    let sum = 0;
    for (let i = 0; i < this.data.cartList.length; i++) {
      for (let j = 0; j < this.data.cartList[i].cart.length; j++) {
        if (this.data.cartList[i].cart[j].check) {
          sum++;
        }
      }
    }
    this.setData({
      checkGoodsNumber: sum
    });
  },
  //--金钱计算
  goodsTotalMoney: function() {
    let len = this.data.cartList.length,
      sum = 0;
    for (let i = 0; i < len; i++) {
      for (let j = 0; j < this.data.cartList[i].cart.length; j++) {
        if (this.data.cartList[i].cart[j].check) {
          sum += this.data.cartList[i].cart[j].price * this.data.cartList[i].cart[j].quantity;
        }
      }
    }
    this.setData({
      totalMoney: sum.toFixed(2)
    });
    this.goodsCheckNumber();
  },
  // 商品选择  
  checkBoxChange: function(et) {
    let query = wx.createSelectorQuery(),
      self = this,
      shop_index = et.currentTarget.dataset.shopindex,
      goods_index = et.currentTarget.dataset.goodsindex;
    if (this.data.cartList[shop_index].cart[goods_index].show_str == 1 && !this.data.goodsChange) {
      this.setData({
        [`cartList[${shop_index}].cart[${goods_index}].check`]: false
      });
      return;
    }
    if (et.detail.value.length != 0) {
      this.setData({
        [`cartList[${shop_index}].cart[${goods_index}].check`]: true
      });
      for (let k = 0; k < this.data.cartList[shop_index].cart.length; k++) {
        if (!this.data.cartList[shop_index].cart[k].check) {
          this.setData({
            [`cartList[${shop_index}].check`]: false,
            allCheck: false
          });
          break;
        }
        if (this.data.cartList[shop_index].cart[k].check && k == this.data.cartList[shop_index].cart.length - 1) {
          this.setData({
            [`cartList[${shop_index}].check`]: true
          });
        }
      }
      _break:
        for (let i = 0; i < this.data.cartList.length; i++) {
          for (let j = 0; j < this.data.cartList[i].cart.length; j++) {
            if (!this.data.cartList[i].cart[j].check) {
              this.setData({
                [`cartList[${i}].check`]: false
              });
              break _break;
            }
            if (this.data.cartList[i].cart[j].check && j == this.data.cartList[i].cart.length - 1) {
              this.setData({
                [`cartList[${i}].check`]: true
              });
            }
          }
          if (i == this.data.cartList.length - 1) {
            this.setData({
              allCheck: true
            });
          }
        }
    } else {
      this.setData({
        [`cartList[${shop_index}].cart[${goods_index}].check`]: false,
        [`cartList[${shop_index}].check`]: false,
        allCheck: false
      });
    }
    this.goodsTotalMoney();
  },
  //--店铺选择
  shopCheck: function(et) {
    let shop_index = et.currentTarget.dataset.shopindex;
    if (et.detail.value.length != 0) {
      this.setData({
        [`cartList[${shop_index}].check`]: true
      });
      this.goodsCheckAllSet(true, shop_index);
      _break:
        for (let i = 0; i < this.data.cartList.length; i++) {
          for (let j = 0; j < this.data.cartList[i].cart.length; j++) {
            if (!this.data.cartList[i].cart[j].check) {
              break _break;
            }
          }
          if (i == this.data.cartList.length - 1) {
            this.setData({
              allCheck: true
            });
          }
        }
    } else {
      this.goodsCheckAllSet(false, shop_index);
      this.setData({
        allCheck: false
      })
    }
    this.goodsTotalMoney();
  },
  // 结算，选择全部
  allCheck: function(et) {
    if (et.detail.value.length != 0) {
      this.setData({
        allCheck: true,
        checkGoodsNumber: this.data.allGoodsNumber
      });
      this.goodsCheckAllSet(true);
    } else {
      this.goodsCheckAllSet(false);
      this.setData({
        allCheck: false,
        checkGoodsNumber: 0
      });
    }
    this.goodsTotalMoney();
  },

  // 编辑
  write: function(et) {
    this.goodsCheckAllSet(false);
    this.isWrite = !this.isWrite
    let a = this.isWrite
    this.setData({
      isWrite: a,
      allCheck: false,
      goodsChange: a,
      checkGoodsNumber: 0
    });
  },
  //--删除批量    
  cartDelGoods: function(et) {
    let self = this,
      cart_ids = [],
      del = [];
    for (let i = 0; i < this.data.cartList.length; i++) {
      for (let j = 0; j < this.data.cartList[i].cart.length; j++) {
        if (this.data.cartList[i].cart[j].check) {
          cart_ids.push(this.data.cartList[i].cart[j].id);
          del.push([i, j]);
        }
      }
    }
    if (cart_ids.length <= 0) {
      api.toast('请选择要删除的商品！');
      return;
    }
    api.ajax(service.url('getCartDelete'), {
      cart_ids: cart_ids.join(",")
    }, function(res) {
      console.log("cart_del：" + JSON.stringify(res));
      if (res.code == 0) {
        api.toast('删除成功！');
        self.init();
      } else {
        api.toast("数据出现错误，删除失败！")
      }
    });
  },
  //--数量更改
  goodsNumberChange: function(id, num, callback) {
    this.setData({
      is_goodsNumber: false
    });
    let self = this,
      cart_id = id || 0,
      quantity = num || 0;
    api.ajax(service.url('cartModNumber'), {
      cart_id: cart_id,
      quantity: quantity
    }, function(res) {
      console.log("modify: " + JSON.stringify(res));
      if (res.code == 0) {
        callback(true);
      } else {
        callback(false);
      }
      self.setData({
        is_goodsNumber: true
      });
    });
  },
  //--数量减
  goodsNumberMinus: function(et) {
    let shop_index = et.currentTarget.dataset.shopindex;
    let goods_index = et.currentTarget.dataset.goodsindex;
    let stock = this.data.cartList[shop_index].cart[goods_index].goods_option[0].stock;
    let num = this.data.cartList[shop_index].cart[goods_index].quantity;
    let cart_id = et.currentTarget.dataset.cartid;
    let _num = num - 1 > 0 ? num - 1 : 1;
    let self = this;
    if (!this.data.is_goodsNumber || num == 1) {
      return;
    }
    if (_num >= 1) {
      this.goodsNumberChange(cart_id, _num, function() {
        self.setData({
          [`cartList[${shop_index}].cart[${goods_index}].quantity`]: _num
        });
        self.goodsTotalMoney();
      });
    }
  },
  //--数量加
  goodsNumberPlus: function(et) {
    let shop_index = et.currentTarget.dataset.shopindex;
    let goods_index = et.currentTarget.dataset.goodsindex;
    let stock = this.data.cartList[shop_index].cart[goods_index].goods_option[0].stock;
    let num = this.data.cartList[shop_index].cart[goods_index].quantity;
    let cart_id = et.currentTarget.dataset.cartid;
    let _num = num + 1;
    let self = this;
    if (!this.data.is_goodsNumber || stock == num) {
      return;
    }
    if (_num <= stock) {
      this.goodsNumberChange(cart_id, _num, function() {
        self.setData({
          [`cartList[${shop_index}].cart[${goods_index}].quantity`]: _num
        });
        self.goodsTotalMoney();
      });
    }
  },
  //--数量输入  
  goodsNumberInput: function(et) {
    if (!this.data.is_goodsNumber) {
      return;
    }
    let val = et.detail.value;
    let shop_index = et.currentTarget.dataset.shopindex;
    let goods_index = et.currentTarget.dataset.goodsindex;
    let stock = this.data.cartList[shop_index].cart[goods_index].goods_option[0].stock;
    let num = this.data.cartList[shop_index].cart[goods_index].quantity;
    let cart_id = et.currentTarget.dataset.cartid;
    let _num = 0;
    let self = this;
    if (!/^[0-9]+$/g.test(val) && val != '') {
      api.toast('请输入合法的数量！');
      self.setData({
        [`cartList[${shop_index}].cart[${goods_index}].quantity`]: num
      });
    } else if (val == '') {
      return;
    } else {
      _num = +val > stock ? stock : +val;
      this.goodsNumberChange(cart_id, _num, function() {
        self.setData({
          [`cartList[${shop_index}].cart[${goods_index}].quantity`]: _num
        });
        self.goodsTotalMoney();
      });
    }
  },
  //--空函数，点击阻止冒泡
  goodsNumberNull: function() {

  },
  //--去上详情
  goGoodsDetail: function(et) {
    let goods_id = et.currentTarget.dataset.goodsid;
    wx.navigateTo({
      url: '../goods_detail/goods_detail?goods_id=' + goods_id
    });
  },
  //--去别人的店铺
  goOtherShop: function(et) {
    let shop_id = et.currentTarget.dataset.shopid;
    wx.reLaunch({
      url: '../index/index?out_user_id=' + shop_id
    });
  },
  //--去确认订单    
  generateOrder: function(et) {
    let cart_ids = [];
    for (let i = 0; i < this.data.cartList.length; i++) {
      for (let j = 0; j < this.data.cartList[i].cart.length; j++) {
        if (this.data.cartList[i].cart[j].check) {
          cart_ids.push(this.data.cartList[i].cart[j].id);
        }
      }
    }
    if (cart_ids.length <= 0) {
      api.toast("你没有选择任何商品，请选择");
      return;
    }
    wx.navigateTo({
      url: '../confirm_order/confirm_order?cart_ids=' + cart_ids.join(",")
    });
  },
  /**
   * 监听用户下拉动作
   */
  onPullDownRefresh: function() {
    wx.showNavigationBarLoading();
    this.init(function() {
      wx.hideNavigationBarLoading();
      wx.stopPullDownRefresh();
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    if (wx.getStorageSync("userInfo") || wx.getStorageSync("shopInfo")) {
      this.init();
    }
  }
})